<template>
  <div class="box">
    <div class="searcharea">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="24">
          <div class="query">
            <el-form :inline="true" :model="queryEquipmentManagementParam" class="demo-form-inline">
              <el-form-item label="设备名称">
                <el-input
                  v-model="queryEquipmentManagementParam.EquipmentName"
                  placeholder="请输入"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :icon="Search" @click="SearchEquipmentManagement()">搜索</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="contentarea">
      <!-- 功能按钮 -->
      <el-row>
        <el-col :span="24">
          <div class="functionbutton">
            <el-button type="primary" plain @click="addEquipmentManagement()">添加</el-button>
            <el-button type="danger" plain @click="batchDeletionEquipmentManagement()">批量删除</el-button>
          </div>
        </el-col>
        <el-dialog
          v-model="centerDialogVisible"
          title="添加设备"
          width="30%"
          align-center
          :before-close="CreateEquipmentManagementhandleClose"
        >
          <el-form
            ref="CreateEquipmentManagementFormRef"
            :model="CreateEquipmentManagementForm"
            :rules="CreateEquipmentManagementRules"
            label-width="auto"
            style="padding: 20px"
          >
            <el-form-item label="设备编号" prop="EquipmentNo">
              <el-input v-model="CreateEquipmentManagementForm.EquipmentNo" placeholder="不输入则自动生成"> </el-input>
            </el-form-item>
            <el-form-item prop="EquipmentName" label="设备名称">
              <el-input v-model="CreateEquipmentManagementForm.EquipmentName" placeholder="请输入设备名称"> </el-input>
            </el-form-item>
            <el-form-item prop="Model" label="设备型号">
              <el-input v-model="CreateEquipmentManagementForm.Model" placeholder="请输入"> </el-input>
            </el-form-item>
            <el-form-item label="所属类别" prop="EquipmentClassifyId" placeholder="请选择">
              <el-select
                v-model="CreateEquipmentManagementForm.EquipmentClassifyId"
                filterable
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="option in EquipmentClassifyOptions"
                  :key="option.key"
                  :label="option.classifyName"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="Description" label="描述">
              <el-input v-model="CreateEquipmentManagementForm.Description" placeholder="请输入"> </el-input>
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="CreateEquipmentManagementhandleClose">取消</el-button>
              <el-button type="primary" @click="CreateEquipmentManagementDialog(CreateEquipmentManagementFormRef)"
                >确认</el-button
              >
            </div>
          </template>
        </el-dialog>
      </el-row>

      <!-- 数据表格 -->
      <el-row>
        <el-col :span="24">
          <div>
            <el-table
              v-loading="tableloading"
              :data="tableData"
              border
              style="width: 100%"
              max-height="400px"
              :selection="selectedRows"
              @selection-change="handleSelectionChange"
              @row-click="getRowkey"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" />
              <el-table-column prop="equipmentNo" label="设备编码" width="180" />
              <el-table-column prop="equipmentName" label="设备名称" width="180" />
              <el-table-column prop="model" label="型号" width="180" />
              <el-table-column prop="equipmentClassify.classifyName" label="设备类别" width="180" />
              <el-table-column prop="workStation.workStationName" label="所在站台" width="180" />
              <el-table-column prop="description" label="描述" width="200" />
              <el-table-column prop="icon" label="状态" align="center">
                <template #default="scope">
                  <!--  状态 选项：0=待机，1=运行中，2=维修中,3=已停用,4=异常 -->
                  <el-button type="info" round size="small" v-if="scope.row.status === 0">待机</el-button>
                  <el-button type="success" round size="small" v-else-if="scope.row.status === 1">运行</el-button>
                  <el-button type="warning" round size="small" v-else-if="scope.row.status === 2">维修</el-button>
                  <el-button type="danger" round size="small" v-else-if="scope.row.status === 3">停用</el-button>
                  <el-button type="danger" round size="small" v-else-if="scope.row.status === 4">异常</el-button>
                </template>
              </el-table-column>

              <el-table-column prop="creator" label="创建人" />
              <el-table-column prop="updator" label="修改人" />
              <el-table-column prop="createtime" label="创建时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="updateDate" label="更新时间" width="180" :formatter="formatColumnTime" />
              <el-table-column fixed="right" label="操作" width="140">
                <template #default="scope">
                  <el-button type="danger" plain size="small" @click="DeleteEquipmentManagementSingle(scope.row.id)">
                    删除
                  </el-button>

                  <el-button type="primary" plain size="small" @click="UpdateEquipmentManagement(scope.row)"
                    >更新</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>

        <el-dialog v-model="UpdateDialogVisible" title="修改设备" width="30%" align-center>
          <el-form
            ref="UpdateEquipmentManagementFormRef"
            :model="UpdateEquipmentManagementForm"
            :rules="CreateEquipmentManagementRules"
            label-width="auto"
            style="padding: 20px"
          >
            <el-form-item label="设备编号" prop="EquipmentNo">
              <el-input v-model="UpdateEquipmentManagementForm.EquipmentNo" disabled placeholder="不输入则自动生成">
              </el-input>
            </el-form-item>
            <el-form-item prop="EquipmentName" label="设备名称">
              <el-input v-model="UpdateEquipmentManagementForm.EquipmentName" placeholder="请输入设备名称"> </el-input>
            </el-form-item>
            <el-form-item prop="Model" label="设备型号">
              <el-input v-model="UpdateEquipmentManagementForm.Model" placeholder="请输入"> </el-input>
            </el-form-item>
            <el-form-item label="所属类别" prop="EquipmentClassifyId" placeholder="请选择">
              <el-select
                v-model="UpdateEquipmentManagementForm.EquipmentClassifyId"
                filterable
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="option in EquipmentClassifyOptions"
                  :key="option.key"
                  :label="option.classifyName"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="Description" label="描述">
              <el-input v-model="UpdateEquipmentManagementForm.Description" placeholder="请输入"> </el-input>
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="UpdateDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="UpdateEquipmentManagementDialog(UpdateEquipmentManagementFormRef)"
                >确认</el-button
              >
            </div>
          </template>
        </el-dialog>
      </el-row>

      <!-- 分页 -->
      <el-row>
        <el-col :span="24">
          <div class="demo-pagination-block" style="display: flex; justify-content: flex-end">
            <el-config-provider :locale="zhCn">
              <el-pagination
                v-model:current-page="queryEquipmentManagementParam.PageIndex"
                v-model:page-size="queryEquipmentManagementParam.PageSize"
                :page-sizes="[100, 200, 300, 400]"
                :small="false"
                :disabled="false"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="queryEquipmentManagementParam.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
              </el-pagination>
            </el-config-provider>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>


<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessageBox, ElNotification, FormInstance } from 'element-plus'
import {
  ApiGetEquipment_EquipmentManagementPageListAsync,
  ApiDeletionEquipment_EquipmentManagementAsync,
  ApiCreateEquipment_EquipmentManagementAsync,
  ApiUpdateEquipment_EquipmentManagementAsync
} from '../../api/equipment/EquipmentManagementApi'
import { formatTime, capitalizeFirstLetter } from '../../utils/index'

import { ApiGetEquipment_EquipmentClassifyPageListAsync } from '../../api/equipment/EquipmentClassifyApi'

// 定义接口和类型
interface EquipmentManagementParam {
  EquipmentName: string | null
  PageIndex: number
  PageSize: number
  totalCount: number
}

interface EquipmentManagement {
  id: string
}

// 响应式变量
const tableloading = ref(false)
const UpdateDialogVisible = ref(false)
const centerDialogVisible = ref(false)
const selectedRows = ref<string[]>([]) // 存储选中的行数据
const CreateEquipmentManagementFormRef = ref<FormInstance>()

// 表单数据和验证规则
const CreateEquipmentManagementForm: EquipmentManagement = reactive({ id: '' })
const UpdateEquipmentManagementForm: EquipmentManagement = reactive({ id: '' })
const CreateEquipmentManagementRules = reactive({
  EquipmentName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  EquipmentClassifyId: [{ required: true, message: '设备类别不能为空', trigger: 'blur' }],
  Model: [{ required: true, message: '设备地址不能为空', trigger: 'blur' }]
})

// 查询参数
const queryEquipmentManagementParam: EquipmentManagementParam = reactive({
  EquipmentName: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 表格数据
const tableData = ref([])

// 分类查询参数
const queryEquipmentClassifyParam = reactive({
  ClassifyName: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})
// 分类下拉框数据
const EquipmentClassifyOptions = ref([])

// 搜索设备
const SearchEquipmentManagement = () => {
  tableloading.value = true
  ApiGetEquipment_EquipmentManagementPageListAsync(queryEquipmentManagementParam)
    .then((res) => {
      tableData.value = res.data.data
      queryEquipmentManagementParam.PageIndex = res.data.pageIndex
      queryEquipmentManagementParam.PageSize = res.data.pageSize
      queryEquipmentManagementParam.totalCount = res.data.totalCount
    })
    .finally(() => {
      tableloading.value = false
    })
}

// 关闭创建设备对话框
const CreateEquipmentManagementhandleClose = () => {
  const formEl = CreateEquipmentManagementFormRef.value
  if (!formEl) return
  formEl.resetFields()
  centerDialogVisible.value = false
}

// 打开添加设备对话框
const addEquipmentManagement = () => {
  centerDialogVisible.value = true

  //获取分类信息
  ApiGetEquipment_EquipmentClassifyPageListAsync(queryEquipmentClassifyParam).then((res) => {
    EquipmentClassifyOptions.value = res.data.data
    queryEquipmentClassifyParam.PageIndex = res.data.pageIndex
    queryEquipmentClassifyParam.PageSize = res.data.pageSize
    queryEquipmentClassifyParam.totalCount = res.data.totalCount
  })
}

// 确认添加设备
const CreateEquipmentManagementDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      ApiCreateEquipment_EquipmentManagementAsync(CreateEquipmentManagementForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '创建成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          CreateEquipmentManagementhandleClose()
          SearchEquipmentManagement()
        }
      })
    }
  })
}

// 打开更新设备信息对话框
const UpdateEquipmentManagement = (row: { [key: string]: string | number }) => {
  Object.assign(UpdateEquipmentManagementForm, capitalizeFirstLetter(row))
  UpdateDialogVisible.value = true

  //获取分类信息
  ApiGetEquipment_EquipmentClassifyPageListAsync(queryEquipmentClassifyParam).then((res) => {
    EquipmentClassifyOptions.value = res.data.data
    queryEquipmentClassifyParam.PageIndex = res.data.pageIndex
    queryEquipmentClassifyParam.PageSize = res.data.pageSize
    queryEquipmentClassifyParam.totalCount = res.data.totalCount
  })
}

// 确认更新设备信息
const UpdateEquipmentManagementFormRef = ref<FormInstance>()
const UpdateEquipmentManagementDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      ApiUpdateEquipment_EquipmentManagementAsync(UpdateEquipmentManagementForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '更新成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          UpdateDialogVisible.value = false
          SearchEquipmentManagement()
        }
      })
    }
  })
}

// 删除单个设备
const DeleteEquipmentManagementSingle = (id: string) => {
  selectedRows.value = [id]
  batchDeletionEquipmentManagement()
}

// 批量删除设备
const batchDeletionEquipmentManagement = () => {
  if (selectedRows.value.length < 1) {
    ElNotification({
      message: '请先选择一条或更多信息',
      type: 'warning',
      offset: 100,
      duration: 2000
    })
    return
  }
  ElMessageBox.confirm('确实要删除这些信息吗?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ApiDeletionEquipment_EquipmentManagementAsync(selectedRows.value)
        .then((res) => {
          if (res.data.data) {
            ElNotification({
              message: '删除成功',
              offset: 100,
              type: 'success',
              duration: 2000
            })
            selectedRows.value = []
            SearchEquipmentManagement()
          }
        })
        .catch(() => {
          selectedRows.value = []
        })
    })
    .catch(() => {
      selectedRows.value = []
    })
}

// 获取用户选择项
const handleSelectionChange = (val: EquipmentManagement[]) => {
  selectedRows.value = val.map((item) => item.id)
}

// 时间转换
const formatColumnTime = (row: object, column: string, time: string | number | Date) => {
  if (time === null) {
    return ''
  }

  if (typeof time === 'string' || typeof time === 'number') {
    return formatTime(time)
  } else {
    return formatTime(time.getTime())
  }
}

// 每页条数
const handleSizeChange = (e: number) => {
  queryEquipmentManagementParam.PageSize = e
  SearchEquipmentManagement()
}

// 当前页变化
const handleCurrentChange = (e: number) => {
  queryEquipmentManagementParam.PageIndex = e
  SearchEquipmentManagement()
}

// 初次加载数据
onMounted(() => {
  SearchEquipmentManagement()
})
</script>



<style lang="less"  scoped>
@import '../../assets/globle/index.css';
</style>
